﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FMPCore;
using System.Windows.Threading;

namespace Client.UserControls
{
    /// <summary>
    /// Interaction logic for ucChat.xaml
    /// </summary>
    public partial class ucChat : UserControl
    {
        public ucChat(string userTalkingWith)
        {
            m_userTalkingWith = userTalkingWith;
            InitializeComponent();
        }

        //public ChatMessage ReceiveMessage
        //{
        //    set 
        //    {
        //        SetReceiveMessage(value);
        //    }
        //}

        private string m_userTalkingWith;
        public string UserTalkingWith
        {
            get { return m_userTalkingWith; }
            //set { m_userTalkingWith = value; }
        }


        public delegate void delegateReceiveMessage(ChatMessage message);

        public void AppendReceivedMessage(ChatMessage message)
        {  
            if(rtbRecive.Dispatcher.CheckAccess())
            {
                // The calling thread owns the dispatcher, and hence the UI element
                using (System.IO.MemoryStream xamlMemoryStream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(message.Message)))
                {
                    System.Windows.Markup.ParserContext parser = new System.Windows.Markup.ParserContext();
                    parser.XmlnsDictionary.Add
                        ("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                    parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
                    //FlowDocument doc = new FlowDocument();

                    Section section = System.Windows.Markup.XamlReader.Load(xamlMemoryStream, parser) as Section;
                    rtbRecive.Document.Blocks.Add(section);
                }
            }
            else
            {
                // Invokation required
                rtbRecive.Dispatcher.Invoke(DispatcherPriority.Normal, new delegateReceiveMessage(AppendReceivedMessage), message);
            }
        }

        public delegate void SendMessageEventHandler(object sender, ChatMessage e);
        public event SendMessageEventHandler SendMessage;

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (SendMessage != null)
            {
                ChatMessage msg = new ChatMessage { To = m_userTalkingWith, Message = ucSend.Message, TimeStamp = DateTime.Now };
                SendMessage(this, msg);
            }
        }
    }
}
